import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import * as QueryFlowAction from '../actions/queryFlow'
import {setNowRouterWfpath} from '../actions/list'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import {Synergy} from 'weaPortal';
import {WeaErrorPage,WeaTools} from 'ecCom'

import {WeaTop,WeaSearchGroup,WeaRightMenu,WeaPopoverHrm,WeaSelect} from 'ecCom'
import {Button, Form, Modal,message} from 'antd'
import CusQueryCondition from'./cloudComponents/wea-wf-cus-query/index.js'
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import Immutable from 'immutable'
const is = Immutable.is;
const fromJS = Immutable.fromJS;
const Map = Immutable.Map;

let _this = null;

class QueryFlow extends React.Component {
    constructor(props) {
        super(props);
        _this = this;
        this.doInit();
    }
    doInit(){
    	const {actions} = this.props;
    	actions.setNowRouterWfpath('queryFlow');
        actions.initCondition();
        actions.clearFormFields();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
    	if(window.location.pathname.indexOf('/spa/workflow/index') >= 0 && nextProps.title && document.title !== nextProps.title)
    		document.title = nextProps.title
        if(keyOld !== keyNew) {
        	this.doInit();
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return !is(this.props.loading, nextProps.loading)
            || !is(this.props.title, nextProps.title)
            || !is(this.props.condition, nextProps.condition)
            || !is(this.props.fields, nextProps.fields)
            || !is(this.props.customid, nextProps.customid)
            || !is(this.props.cusOption, nextProps.cusOption)
            || !is(this.props.cusCondition, nextProps.cusCondition);
    }
    componentWillUnmount() {
        this.props.actions.clearAllState();
    }
    render() {
        const isSingle = window.location.pathname.indexOf('/spa/workflow/index') >= 0;
        const {actions,loading,title,fields} = this.props;
        return (
            <div className='wea-workflow-query'>
            	{isSingle && <WeaPopoverHrm />}
            	<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                <WeaTop
                	title={title}
                	loading={loading}
                	icon={<i className='icon-portal-workflow' />}
                	iconBgcolor='#55D2D4'
                	buttons={[]}
                	buttonSpace={10}
                	showDropIcon={true}
                	dropMenuDatas={this.getRightMenu()}
                	onDropMenuClick={this.onRightMenuClick.bind(this)} >
                    <div className='wea-workflow-query-search'>
                        <Form horizontal>{this.getSearchs()}</Form>
                        <div className='wea-workflow-query-btns'>
                            {this.getSearchButtons()}
                        </div>
                    </div>
                </WeaTop>
                </WeaRightMenu>
                <Synergy pathname='/workflow/queryFlow' requestid="-1" />
            </div>
        )
    }
    onRightMenuClick(key){
    }
    getRightMenu(){
    	const { actions } = this.props;
    	let btns = [];
    	btns.push({
            key: "search",
    		icon: <i className='icon-workflow-Right-menu--search'/>,
            content:'搜索',
            onClick: key =>{
                this.forwardQueryResult();
            }
    	});
    	return btns
    }
    getSearchs() {
        const { condition,customid,cusOption,cusCondition } = this.props;
		let group = [];
		condition.map(v =>{
			let items = [];
			v.get("items").map(item => {
                const fields = item.toJS();
				items.push({
	                com:(<FormItem
                            label={`${fields.label}`}
	                        labelCol={{span: `${fields.labelcol}`}}
	                        wrapperCol={{span: `${fields.fieldcol}`}}>
                        {WeaTools.getComponent(fields.conditionType, fields.browserConditionParam, fields.domkey, this.props, fields)}
	                    </FormItem>),
	                colSpan:1
	            });
			});
			group.push(<WeaSearchGroup needTigger={true} title={v.get("title")} showGroup={v.get("defaultshow")} items={items}/>);
        });
        if(cusOption && cusOption.size > 0 && cusCondition && cusCondition.size > 0){  //自定义查询条件
            let cusitems = [];
            cusCondition.map(item =>{
                const fields = item.toJS();
                item.get("otherParams").map((v,k) =>{
                    fields[k] = v;
                });
                cusitems.push({
                    com: (<FormItem
                            label={`${fields.label}`}
                            labelCol={{span: `${fields.labelcol}`}}
                            wrapperCol={{span: `${fields.fieldcol}`}}>
                            {fields.conditionType === "CUSTOM" ?
                                <CusQueryCondition {...fields} form={this.props.form} /> :
                            WeaTools.getComponent(fields.conditionType, fields.browserConditionParam, fields.domkey, this.props, fields)}
	                    </FormItem>)
                });
            });
            let customComponent = <WeaSelect options={cusOption.toJS()} value={customid} onChange={this.changeCustomid.bind(this)} />;
            group.push(<WeaSearchGroup needTigger={true} title="自定义查询条件" showGroup={true} items={cusitems} customComponent={customComponent}/>);
        }
		return group;
    }
    getSearchButtons() {
        const { actions} = this.props;
        const btnStyle = {borderRadius: 3, height: 28, width: 80}
        return [
            (<Button type="primary" style={btnStyle} onClick={()=>{this.forwardQueryResult();}}>搜索</Button>),
            (<span style={{width:'15px', display:'inline-block'}}></span>),
            (<Button type="ghost" style={btnStyle} onClick={()=>{actions.clearFormFields();}}>重置</Button>)
        ]
    }
    forwardQueryResult(){
        const {fields,condition,customid,cusOption,cusCondition} = this.props;
        this.props.history.push({
            pathname: "/main/workflow/queryFlowResult",
            query: {fromwhere:"queryFlow"},
            state: {fields,condition,customid,cusOption,cusCondition}
        });
    }
    changeCustomid(value){
        this.props.actions.changeCustomid(value);
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

QueryFlow = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(QueryFlow);

QueryFlow = createForm({
    onFieldsChange(props, changeFields) {
        const originalFields = props.fields;
        if(changeFields && "workflowid" in changeFields){
            const oldWfid = originalFields && originalFields.getIn(["workflowid","value"]) || "";
            const newWfid = changeFields && changeFields.workflowid.value;
            if(oldWfid != newWfid){ //改变了工作流
                //props.actions.loadCustomCondition({type:"changeWf", workflowid:newWfid});
            }
        }
        props.actions.appendFormFields(changeFields);
    },
    mapPropsToFields(props) {
        return props.fields.toJS();
    }
})(QueryFlow);

function mapStateToProps(state) {
    const {workflowqueryFlow} = state;
    return {
    	loading: workflowqueryFlow.get('loading'),
        title: workflowqueryFlow.get('title'),
        condition: workflowqueryFlow.get('condition'),
        fields: workflowqueryFlow.get('fields'),
        customid: workflowqueryFlow.get('customid'),
        cusOption: workflowqueryFlow.get('cusOption'),
        cusCondition: workflowqueryFlow.get('cusCondition')
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...QueryFlowAction,setNowRouterWfpath}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(QueryFlow);